package com.demo.arch.datapulsedemo.v3_reliable.example;

import com.demo.arch.datapulsedemo.common.TaskResult;
import com.demo.arch.datapulsedemo.v2_pipeline.core.PipelineContext;
import com.demo.arch.datapulsedemo.v3_reliable.core.ContextStorage;
import com.demo.arch.datapulsedemo.v3_reliable.core.ReliablePipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * V3版本简化示例控制器
 * 
 * @author DataPulse Team
 */
@Slf4j
@RestController
@RequestMapping("/v3/example")
public class SimpleExampleController {

  @Autowired
  private ReliablePipeline pipeline;

  @Autowired
  private ContextStorage contextStorage;

  /**
   * 演示V3版本核心功能
   * 
   * 测试URL: http://localhost:8080/v3/example
   */
  @GetMapping("")
  public Map<String, Object> showFeatures() {
    Map<String, Object> result = new HashMap<>();
    result.put("title", "V3版本 - 轻量级可靠增强");
    result.put("description", "专注于任务级别的断点续跑和幂等性保证");

    // 核心特性
    Map<String, String> features = new HashMap<>();
    features.put("断点续跑", "任务执行中断后，可以从上次失败点继续执行");
    features.put("幂等性保证", "重新执行任务时，已完成的步骤会被跳过");
    features.put("邮件幂等", "已发送成功的邮件不会重复发送");
    features.put("状态管理", "提供任务状态查询和恢复接口");
    result.put("features", features);

    // API接口
    Map<String, String> apis = new HashMap<>();
    apis.put("GET /v3/report?type=日报", "执行报表任务");
    apis.put("POST /v3/task/recover/{taskId}", "从断点恢复任务");
    apis.put("GET /v3/task/status/{taskId}", "查询任务状态");
    apis.put("GET /v3/task/failed", "查询失败任务列表");
    result.put("apis", apis);

    // 设计理念
    Map<String, String> design = new HashMap<>();
    design.put("简单直接", "不引入复杂的Outbox模式和定时任务");
    design.put("外部服务", "邮件发送通过Feign调用外部服务（模拟）");
    design.put("任务级可靠", "重点保证任务可以恢复，而非邮件级自动重试");
    design.put("轻量存储", "使用文件系统存储任务状态，无需数据库");
    result.put("design", design);

    return result;
  }

  /**
   * 创建模拟失败任务
   * 
   * 测试URL: http://localhost:8080/v3/example/create-failed-task
   */
  @GetMapping("/create-failed-task")
  public TaskResult createFailedTask() {
    log.info("=== 创建模拟失败任务 ===");

    String taskId = "FAILED_" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();

    PipelineContext context = new PipelineContext("测试报表");
    context.setTaskId(taskId);
    context.setCreateTime(LocalDateTime.now());
    context.setCurrentStep(2);
    context.setErrorMessage("模拟的失败任务，用于测试断点续跑");

    contextStorage.save(context);

    log.info("=== 模拟失败任务已创建: {} ===", taskId);

    Map<String, Object> data = new HashMap<>();
    data.put("taskId", taskId);
    data.put("message", "模拟失败任务已创建");
    data.put("recoverUrl", "/v3/task/recover/" + taskId);
    data.put("statusUrl", "/v3/task/status/" + taskId);

    return TaskResult.success("模拟失败任务已创建", data);
  }

  /**
   * 查询所有失败任务
   * 
   * 测试URL: http://localhost:8080/v3/example/list-failed-tasks
   */
  @GetMapping("/list-failed-tasks")
  public TaskResult listFailedTasks() {
    log.info("=== 查询所有失败任务 ===");

    List<String> failedTasks = contextStorage.findFailedTasks();

    log.info("=== 发现{}个失败任务 ===", failedTasks.size());

    Map<String, Object> data = new HashMap<>();
    data.put("failedTasks", failedTasks);
    data.put("count", failedTasks.size());

    return TaskResult.success("查询失败任务成功", data);
  }

  /**
   * 测试Pipeline执行
   * 
   * 测试URL: http://localhost:8080/v3/example/test-pipeline
   */
  @GetMapping("/test-pipeline")
  public TaskResult testPipeline() {
    log.info("=== 测试Pipeline执行 ===");

    TaskResult result = pipeline.execute("示例报表");

    log.info("=== Pipeline执行结果: {} ===", result.isSuccess() ? "成功" : "失败");
    return result;
  }
}
